package Base64;

import org.junit.Test;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;
import java.util.UUID;

public class TestBase64 {
    public static void main(String[] args) {

    }

    @Test
    public void testEncoder(){
        String str = "你在想什么";
        //使用基本编码
        String easyEncoder = Base64.getEncoder().encodeToString(str.getBytes());
        System.out.println("Base64 编码字符串(基本):"+easyEncoder);
        //使用基本解码
        byte[] decode = Base64.getDecoder().decode(easyEncoder);
        String easyDecode = new String(decode);
        System.out.println("Base64 解码，原始字符串:"+easyDecode);
    }

    @Test
    public void testUrlEncoder(){
        String str = "你快乐了嘛";
        //URL 方式编码
        String urlEncoder = Base64.getUrlEncoder().encodeToString(str.getBytes());
        System.out.println("Base64 编码字符串(URL):"+urlEncoder);
        //URL方式解码
        byte[] decode = Base64.getUrlDecoder().decode(urlEncoder);
        String urlDecode = new String(decode);
        System.out.println("Base64 解码，原始字符串:"+urlDecode);
    }
    @Test
    public void testMimeEncoder(){
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 2; i++) {
            stringBuilder.append(UUID.randomUUID().toString().replace("-",""));
        }
        System.out.println("stringBuilder:"+stringBuilder);
        //Mime 方式编码
        String mimeEncoder = Base64.getMimeEncoder().encodeToString(new String(stringBuilder).getBytes());
        System.out.println("Base64 编码字符串(Mime):"+mimeEncoder);
        //Mime 方式解码
        byte[] decode = Base64.getMimeDecoder().decode(mimeEncoder);
        String MimeDecode = new String(decode);
        System.out.println("Base64 解码，原始字符串:"+MimeDecode);
    }

    @Test
    public void testImage2Base64(){
        String fromPath = "D:\\good.png";
        String toPath ="D:\\cc\\excellent.png";
        String s = fileToBase64Str(fromPath);
        System.out.println("图片转换以后的Base64:"+s);
        base64StrToFile(s,toPath);
    }
    @Test
    public void testBase642Image(){
        String base64 ="";
        String path ="D:\\excellent.png";
        base64StrToFile(base64,path);
    }


    /**
     * 文件转化成base64字符串
     *
     * @param path 文件路径
     * @return String base64字符串
     */
    public static String fileToBase64Str(String path) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(new File(path));
            data = new byte[in.available()];
            in.read(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对字节数组Base64编码
        return Base64.getMimeEncoder().encodeToString(data);
    }

    /**
     * 将base64字符串转换为文件并存储到指定位置
     *
     * @param base64Str base64字符串
     * @param filePath  文件路径
     * @return boolean true表示转换成功，false表示转换失败
     */
    public static boolean base64StrToFile(String base64Str, String filePath) {
        if (base64Str == null && filePath == null) {
            return false;
        }
        try {
            Files.write(Paths.get(filePath), Base64.getMimeDecoder().decode(base64Str), StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }




    public static boolean GenerateImage(String imgStr,String path)
    {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //新生成jpeg图片
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

}
